#include"DListNode.h"

ListNode* CreateListNode(DLTDatatype x) {
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL) {
		perror("malloc false");
		return NULL;
	}
	newnode->next = NULL;
	newnode->prev = NULL;
	newnode->data = x;
	return newnode;
}

ListNode* InitList() {
	ListNode*phead = CreateListNode(-1);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void PrintList(ListNode* phead) {
	assert(phead);
	ListNode* cur = phead->next;
	printf("head<=>");
	while (cur != phead) {
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

bool IsEmpty(ListNode* phead) {
	assert(phead);
	return phead->next == phead;
}
ListNode*FindNode(ListNode* phead, DLTDatatype x) {
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead) {
		if (cur->data == x) {
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void pushrear(ListNode* phead, DLTDatatype x) {
	assert(phead);
	ListNode* newnode = CreateListNode(x);
	ListNode* tail = phead->prev;
	newnode->next = phead;
	tail->next = newnode;
	newnode->prev = tail;
	phead->prev = newnode;
	/*Insert(phead, phead, x);*/
}

void poprear(ListNode* phead) {
	assert(phead);
	assert(!IsEmpty(phead));
	ListNode* tail = phead->prev;
	ListNode* tailprev = tail->prev;
	tailprev->next = phead;
	phead->prev = tailprev;
	free(tail);
	tail = NULL;
	/*Earse(phead, phead->prev);*/
}

void pushfront(ListNode* phead, DLTDatatype x) {
	
	assert(phead);
	ListNode* newnode = CreateListNode(x);
	ListNode* tailnext = phead->next;
	newnode->next = tailnext;
	tailnext->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;
	/*Insert(phead, phead->next, x);*/
}

void popfront(ListNode* phead) {
	assert(phead);
	assert(!IsEmpty(phead));
	ListNode* tail = phead->next;
	ListNode* tailnext = tail->next;
	phead->next = tailnext;
	tailnext->prev = phead;
	free(tail);
	tail = NULL;
	/*Earse(phead, phead->next);*/
}

void Insert(ListNode* phead, ListNode* pos, DLTDatatype x) {
	assert(phead);
	assert(pos);
	ListNode* per = pos->prev;
	ListNode* newnode = CreateListNode(x);
	per->next = newnode;
	newnode->prev = per;
	newnode->next = pos;
	pos->prev = newnode;
}

void Earse(ListNode* phead, ListNode* pos) {
	assert(phead);
	assert(pos);
	ListNode* pre = pos->prev;
	ListNode* cur = pos->next;
	pre->next = cur;
	cur->prev = pre;
	free(pos);
}

void Destroy(ListNode* phead) {
	assert(phead);
	ListNode* cur = phead->next;
	ListNode* t;
	while (cur != phead) {
		t = cur->next;
		free(cur);
		cur = t;
	}
	free(phead);
}
